package benny.ApkposStore.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ConfigDBHelper {
	public static final String TAG = "ConfigDBHelper";

	public static final int DB_VERSION = 1;
	//public static final String DB_NAME = "shop_config.db"; // DB文件名
	private static SQLiteDatabase mDB = null;

	public static void close() {
		if (mDB != null) {
			try {
				mDB.close();			
				mDB = null;
			} catch (Exception e) {
				// TODO: handle exception
				return;
			}
			
		}
	}
	
	/**
	 * @param context 这里的Context一定要用ApplicationContext
	 * @return
	 */
	public static synchronized SQLiteDatabase getWritableDatabase(Context AppContext,String name) {
			
		if (mDB == null || !mDB.isOpen()) {
				mDB = (new DatabaseHelper(AppContext,name)).getWritableDatabase();		
			}
			

		return mDB;
	}
	public static synchronized SQLiteDatabase getReadableDatabase(Context AppContext,String name) {
		
		if (mDB == null || !mDB.isOpen()) {
		
				mDB = (new DatabaseHelper(AppContext,name)).getReadableDatabase();	
			
		}
		return mDB;
	}

	/**
	 * query whether the sqlite table is  exist
	 * @param tableName
	 * @param db
	 * @return true if table already exist
	 */
	public static  boolean isTableExist(String tableName, SQLiteDatabase db) {
        boolean result = false;
        if(tableName == null){
                return false;
        }
        
        Cursor cursor = null;
        try {
            String sql = "select count(*) as c from sqlite_master where type ='table' and name ='"+ tableName.trim()+"' ";
            cursor = db.rawQuery(sql, null);
            if(cursor.moveToNext()){
                int count = cursor.getInt(0);
                if(count>0){
                        result = true;
                }
            }                
        } catch (Exception e) {
                // TODO: handle exception
        }                
        return result;		
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper {

		// 这里的Context一定要用ApplicationContext
		DatabaseHelper(Context context,String name) {
			super(context, name, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			System.out.println("create a Database");
			return;
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			System.out.println("Upgrade a Database");
			return;
		}
		

	}

}
